import util from '@/libs/util';
import CONSTANTS from '@/config/constants';
import Cookies from 'js-cookie';
import UEditor from '@/util/ueditor.vue';

export default {
    name: 'exportable-table',
    components: {UEditor},
    data () {
        return {
            columns: [{
                title: '序号',
                key: 'rownum',
                width: 60,
                align: 'center',
                render: (h, params) => {
                    return h('div', {}, ((this.pageIndex - 1) * this.pageSize + params.index + 1));
                }
            }, {
                title: '活动名称',
                key: 'name',
                ellipsis: true,
                render: (h, params) => {
                    return h('Tooltip', {props: {placement: 'top-start'}}, [
                        h('div', {style: {'white-space': 'nowrap'}}, params.row.name),
                        h('div', {slot: 'content', style: {'white-space': 'normal'}}, params.row.name)
                    ]);
                }
            }, {
                title: '活动类型',
                key: 'typename',
                width: 85
            }, {
                title: '活动时间',
                key: 'days',
                width: 85,
                ellipsis: true,
                render: (h, params) => {
                    return h('Tooltip', {
                        props: {
                            placement: 'top-start',
                            content: params.row.days
                        }
                    }, params.row.days);
                }
            }, /*{
                title: '交通方式',
                key: 'vehiclename',
                width: 85
            },*/ {
                title: '截止时间',
                key: 'applyendtime'
            }, {
                title: '出发时间',
                key: 'departtime'
            }, {
                title: '是否发布',
                key: 'releases',
                width: 85,
                render: (h, params) => {
                    return h('div', {}, (params.row.releases === 'YES' ? '是' : '否'));
                }
            }, {
                title: '是否推荐',
                key: 'recommend',
                width: 85,
                render: (h, params) => {
                    return h('div', {}, (params.row.recommend === 1 ? '是' : '否'));
                }
            }, {
                title: '状态',
                key: 'status',
                width: 85,
                render: (h, params) => {
                    let texts = '';
                    if (params.row.status === 'APPLYING') {
                        texts = '正在报名';
                    } else if (params.row.status === 'END') {
                        texts = '结束';
                    }
                    return h('div', {}, texts);
                }
            }, {
                title: '操作',
                key: 'action',
                width: 350,
                align: 'center',
                render: (h, params) => {
                    return h('div', [
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px',
                                display: (params.row.releases === 'YES' ? 'none' : 'inline')
                            },
                            on: {
                                click: () => {
                                    this.issue(params.row.id);
                                }
                            }
                        }, '发布'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px',
                                display: (params.row.releases === 'YES' ? 'inline' : 'none')
                            },
                            on: {
                                click: () => {
                                    this.recommend(params.row.id, params.row.recommend);
                                }
                            }
                        }, (params.row.recommend === 1 ? '取消推荐' : '推荐')),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px',
                                display: (params.row.releases === 'YES' && params.row.status === 'APPLYING' ? 'inline' : 'none')
                            },
                            on: {
                                click: () => {
                                    this.update(params.row.id, {
                                        status: 'END',
                                        recommend: 2,
                                        releases: 'NO'
                                    }, '活动结束成功！');
                                }
                            }
                        }, '结束活动'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.setPrice(params.row.id, params.row.status);
                                }
                            }
                        }, '价格'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.detail(params.row.id);
                                }
                            }
                        }, '详情'),
                        h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                marginRight: '5px'
                            },
                            on: {
                                click: () => {
                                    this.showEdit(params.row);
                                }
                            }
                        }, '修改'),
                        h('Button', {
                            props: {
                                type: 'error',
                                size: 'small'
                            },
                            on: {
                                click: () => {
                                    this.delete(params.row.id);
                                }
                            }
                        }, '删除')
                    ]);
                }
            }],
            data: [],
            formData: {isidcard: 'NO'},
            viewModalVisible: false,
            saveModalVisible: false,
            priceModalVisible: false,
            isSelect: true,
            isInput: false,
            showImg: false,

            total: 0,
            pageIndex: 1,
            pageSize: 10,
            queryCon: {
                activityName: '',
                type: '',
                vehicle: '',
                release: '',
                state: '',
                order: '',
                recommend: ''
            },
            typeList: [],
            vehicleList: [],
            ledTeacherList: [],
            activeObjectList: [],
            insuranceList: [],
            timeList: [],
            uploadList: [],
            priceList: [],
            activityId: '',
            imgUrl: '',
            SERVER_HOST: CONSTANTS.SERVER_HOST,
            config: {
                scaleEnabled: true,
                autoFloatEnabled: true,
                initialContent: '',
                autoClearinitialContent: true,
                initialFrameWidth: null,
                initialFrameHeight: 450,
                BaseUrl: '',
                UEDITOR_HOME_URL: '/static/ueditor/'
            }
        };
    },
    mounted () {
        this.loadList();
    },
    methods: {
        loadList() {
            util.ajax.post('/busine/activity/list', util.toFormData({
                page: this.pageIndex,
                size: this.pageSize,
                activityName: this.queryCon.activityName,
                type: this.queryCon.type,
                vehicle: this.queryCon.vehicle,
                release: this.queryCon.release,
                state: this.queryCon.state,
                order: this.queryCon.order,
                recommend: this.queryCon.recommend,
                orgId: eval('(' + Cookies.get('baseUser') + ')').orgId,
                bs: 2
            })).then(res => {
                var lists = res.data.data.pageInfo.list;
                for (var i = 0; i < lists.length; i++) {
                    if (lists[i].type) {
                        lists[i]['typename'] = lists[i].type.name;
                    }
                    if (lists[i].vehicle) {
                        lists[i]['vehiclename'] = lists[i].vehicle.name;
                    }
                    lists[i]['applyendtime'] = this.getDate(lists[i].applyendtime);
                    lists[i]['departtime'] = lists[i].departtime.split(',')[0];
                }
                this.data = res.data.data.pageInfo.list;
                this.total = res.data.data.pageInfo.total;
                this.typeList = res.data.data.typeList;
                this.vehicleList = res.data.data.vehicleList;
                this.activeObjectList = res.data.data.activeObjectList;
                this.ledTeacherList = res.data.data.ledTeacherList;
                this.insuranceList = res.data.data.insuranceList;
            });
        },
        detail(id) {
            let _this = this;
            util.ajax.post('/busine/activity/detail', util.toFormData({
                id: id
            })).then(res => {
                if (res.data.data) {
                    var li = res.data.data;
                    if (li.type) {
                        li["typename"] = li.type.name;
                    }
                    if (li.vehicle) {
                        li["vehiclename"] = li.vehicle.name;
                    }
                    if (li.ledTeacher) {
                        li["ledTeachername"] = li.ledTeacher.name;
                    } else {
                        li["ledTeachername"] = li.ledteacher
                    }
                    if (li.activeObject) {
                        li["activeObjectname"] = li.activeObject.name;
                    }
                    if (li.platformManage) {
                        li["platformManageAppid"] = li.platformManage.appid;
                    }
                    li['applyendtime1'] = li['applyendtime'] = this.getDate(li.applyendtime);
                    li['departendtime1'] = li['departendtime'] = this.getDate(li.departendtime);
                    li['discounttime1'] = li['discounttime'] = this.getDate(li.discounttime);
                    this.uploadList = [];
                    this.$refs.upload.fileList = [];
                    if (li.cover) {
                        let list = li.cover.split('@');
                        list.forEach(item => {
                            this.uploadList.push({
                                status: 'finished',
                                'url': this.SERVER_HOST + item,
                                path: item
                            });
                        });
                    }
                    _this.formData = res.data.data;
                    _this.viewModalVisible = true;
                } else {
                    _this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        showAdd() {
            this.formData = {};
            this.formData["isidcard"] = 'NO';
            this.formData["releases"] = 'NO';
            this.formData["isinsurance"] = 0;
            this.timeList = [{value: ''}];
            this.uploadList = [];
            this.$refs.upload.fileList = [];
            // this.$refs.activity_intro.setUEContent("");
            this.$refs.activity_speaker.setUEContent("");
            this.$refs.activity_scheduling.setUEContent("");
            this.saveModalVisible = true;
        },
        showEdit(obj) {
            this.timeList = [];
            this.formData = {};
            util.ajax.post('/busine/activity/detail', util.toFormData({
                id: obj.id
            })).then(res => {
                if (res.data.data) {
                    var li = res.data.data;
                    if (li.type) {
                        li["typeId"] = li.type.id;
                    }
                    if (li.vehicle) {
                        li["vehicleId"] = li.vehicle.id;
                    }
                    if (li.ledTeacher) {
                        li["ledteacherId"] = li.ledTeacher.id;
                        this.isInput = false;
                        this.isSelect = true;
                    } else if (li.ledteacher != '') {
                        this.isInput = true;
                        this.isSelect = false;
                    } else {
                        this.isInput = false;
                        this.isSelect = true;
                    }
                    if (li.activeObject) {
                        li["activeobjectId"] = li.activeObject.id;
                    }
                    li['applyendtime'] = this.getDate(li.applyendtime);
                    li['departendtime'] = this.getDate(li.departendtime);
                    li['discounttime'] = this.getDate(li.discounttime);

                    let timeArray = li.departtime.split(',');
                    let timeList = [{value: ''}];
                    for (let i = 0; i < timeArray.length; i++) {
                        timeList[i] = {value: timeArray[i]};
                    }
                    this.timeList = timeList;
                    this.uploadList = [];
                    this.$refs.upload.fileList = [];
                    if (li.cover) {
                        let list = li.cover.split('@');
                        list.forEach(item => {
                            this.uploadList.push({
                                status: 'finished',
                                'url': this.SERVER_HOST + item,
                                path: item
                            });
                        });
                    }
                    this.formData = res.data.data;
                    // this.$refs.activity_intro.setUEContent(this.formData.intro);
                    this.$refs.activity_speaker.setUEContent(this.formData.speaker);
                    this.$refs.activity_scheduling.setUEContent(this.formData.scheduling);
                    this.saveModalVisible = true;
                } else {
                    this.$Modal.error({
                        title: '警告',
                        content: '出错了'
                    });
                }
            });
        },
        destroyed() {
            this.saveModalVisible = false;
        },
        activitySave() {
            let formData = {};
            for (let key in this.formData) {
                formData[key] = this.formData[key];
            }
            let departtime = '';
            let timeList = this.timeList;
            for (var i = 0; i < timeList.length; i++) {
                if (timeList[i].value != '') {
                    if (departtime != '') departtime = departtime + ',';
                    departtime = departtime + this.getDate(timeList[i].value);
                }
            }
            formData['departtime'] = departtime;
            if (this.isSelect == false || formData['ledteacherId'] == '') {
                formData['ledteacherId'] = '-1';
            }
            let baseuser = eval('(' + Cookies.get('baseUser') + ')');
            if (baseuser.orgId) {
                formData['orgId'] = baseuser.orgId;
            }
            formData['bs'] = 2;
            // formData['intro'] = this.$refs.activity_intro.getUEContent();
            formData['speaker'] = this.$refs.activity_speaker.getUEContent();
            formData['scheduling'] = this.$refs.activity_scheduling.getUEContent();
            util.ajax.post('/busine/activity/save', util.toFormData(formData)).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.saveModalVisible = false;
                    this.$Message.success('保存成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
        },
        delete(id) {
            this.$Modal.confirm({
                title: '提示',
                content: '<p>确定删除？</p>',
                onOk: () => {
                    util.ajax.post('/busine/activity/delete', util.toFormData({
                        id: id
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('删除成功！');
                            this.loadList();
                        }
                    });
                },
                onCancel: () => {
                }
            });
        },
        getDate(data) {
            let myDate;
            if (data instanceof Date) {
                myDate = data;
            } else if (typeof(data) == 'number') {
                myDate = new Date(data);
            } else {
                return data;
            }

            let Y = myDate.getFullYear(),
                M = myDate.getMonth() + 1,
                D = myDate.getDate(),
                H = myDate.getHours(),
                Min = myDate.getMinutes(),
                S = myDate.getSeconds();

            if (M < 10) {
                M = '0' + M;
            }
            if (D < 10) {
                D = '0' + D;
            }
            if (H < 10) {
                H = '0' + H;
            }
            if (Min < 10) {
                Min = '0' + Min;
            }
            if (S < 10) {
                S = '0' + S;
            }
            return Y + '-' + M + '-' + D;
        },
        addTime() {
            const time = {value: ''};
            const timeList = this.timeList;
            this.timeList.splice(timeList.length, 0, time);
        },
        delTime() {
            const timeList = this.timeList;
            if (timeList.length > 0) {
                this.timeList.splice(timeList.length - 1, 1);
            }
        },
        handleSuccess(res, file) {
            let strUrls = '';
            this.uploadList.forEach(item => {
                strUrls += (item.path + '@');
            });
            this.uploadList.push({
                showProgress: true
            });
            var listSize = this.uploadList.length;
            var xmlhttp = null;
            var urlPath = this.SERVER_HOST + res.data.imgUrl;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            }
            let interval = setInterval(() => {
                xmlhttp.open('GET', urlPath, false);
                xmlhttp.send();
                if ((xmlhttp.readyState === 4 && xmlhttp.status === 200)) {
                    clearInterval(interval);
                    this.$Notice.success({
                        title: '文件上传成功',
                        desc: '文件 ' + file.name + ' 上传成功。',
                        duration: 2
                    });
                    file['path'] = res.data.imgUrl;
                    file['url'] = this.SERVER_HOST + res.data.imgUrl;
                    file['name'] = res.data.fileName;
                    this.$refs.upload.fileList[listSize - 1] = file;
                    this.uploadList.splice(-1, 1, this.$refs.upload.fileList[listSize - 1]);
                    strUrls += res.data.imgUrl;
                    this.formData['cover'] = strUrls;
                }
            }, 500);
        },
        handleFormatError(file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请选择图片文件。',
                duration: 5
            });
        },
        handleMaxSize(file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                duration: 5
            });
        },
        handleRemove(index) {
            this.uploadList.splice(index, 1);
            this.$refs.upload.fileList.splice(index, 1);
            let strUrls = '';
            this.uploadList.forEach(item => {
                if (strUrls !== '') strUrls += '@';
                strUrls += item.path;
            })
            this.formData['cover'] = strUrls;
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。',
                    duration: 5
                });
            }
            return check;
        },
        refresh() {
            this.queryCon = {
                activityName: '',
                type: '',
                vehicle: '',
                release: '',
                state: '',
                order: '',
                recommend: ''
            };
            this.loadList();
        },
        setPrice(id, status) {
            this.activityId = id;
            let _this = this;
            util.ajax.post('/busine/price/listByActivity', util.toFormData({
                id: id,
                status: status
            })).then(res => {
                if (res.data.message === 'SUCCESS') {
                    if (res.data.data) {
                        _this.priceList = res.data.data;
                        if (_this.priceList.length == 0) {
                            _this.priceList.splice(0, 0, {
                                name: '',
                                money: 0,
                                peoplenums: 0
                            });
                        }
                        this.priceModalVisible = true;
                    }
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }

            })
        },
        addPrice() {
            this.priceList.push({
                name: '',
                money: 0,
                peoplenums: 0
            });
        },
        delPrice() {
            const priceList = this.priceList;
            if (priceList.length > 0) {
                this.priceList.splice(priceList.length - 1, 1);
            }
            if (priceList.length == 0) {
                this.priceList.splice(0, 0, {
                    name: '',
                    money: 0,
                    peoplenums: 0
                });
            }
        },
        priceSave() {
            let _this = this;
            let priceList = [];
            for (let i = 0; i < _this.priceList.length; i++) {
                if (_this.priceList[i].name != "" && _this.priceList[i].money != "") {
                    priceList.push(_this.priceList[i]);
                }
            }
            util.ajax.post('/busine/price/saveByActivity', util.toFormData({
                id: _this.activityId,
                listStr: JSON.stringify(priceList)
            })).then(res => {
                if (res.data.message === 'SUCCESS') {
                    this.saveModalVisible = false;
                    this.$Message.success('保存成功！');
                    this.loadList();
                } else {
                    this.$Message.warning(res.data.message || '未知错误！');
                }
            });
            this.priceModalVisible = false;
        },
        priceCancel() {
            this.priceModalVisible = false;
        },
        issue(id) {
            let _this = this;
            util.ajax.post('/busine/price/listByActivity', util.toFormData({
                id: id
            })).then(res => {
                let priceData = res.data.data
                let sumPrice = 0;
                for (let i = 0; i < priceData.length; i++) {
                    sumPrice += priceData[i].money;
                }
                if (sumPrice == 0) {
                    _this.$Modal.confirm({
                        title: '警告',
                        content: '未设置价格，是否继续发布！',
                        okText: '继续',
                        onOk: () => {
                            util.ajax.post('/busine/activity/issue', util.toFormData({
                                id: id
                            })).then(res => {
                                if (res.data.message === 'SUCCESS') {
                                    this.$Message.success('发布成功！');
                                    this.loadList();
                                } else {
                                    this.$Message.warning(res.data.message || '未知错误！');
                                }
                            })
                        }
                    });
                } else {
                    util.ajax.post('/busine/activity/issue', util.toFormData({
                        id: id
                    })).then(res => {
                        if (res.data.message === 'SUCCESS') {
                            this.$Message.success('发布成功！');
                            this.loadList();
                        } else {
                            this.$Message.warning(res.data.message || '未知错误！');
                        }
                    })
                }
            })
        },
        teacherSelect(data) {
            this.formData.ledteacher = data
            let list = this.ledTeacherList.filter(item => item.name.indexOf(data) > -1);
            if (list.length == 0) {
                this.isSelect = false;
                this.isInput = true;
                this.formData.ledteacherId = '';
                this.formData.teacherphone = '';
            }
        },
        teacherInput(data) {
            if (!(data.data)) {
                this.isSelect = true;
                this.isInput = false;
            }
        },
        teacherPhone(data) {
            for (var i = 0; i < this.ledTeacherList.length; i++) {
                if (data == this.ledTeacherList[i].id) {
                    this.formData.teacherphone = this.ledTeacherList[i].phone;
                }
            }
        },
        openImg (imgUrl) {
            this.imgUrl = imgUrl;
            this.showImg = true;
        },
        recommend (id, recommend) {
            let formData = [];
            if (recommend === 1) {
                formData['recommend'] = 2;
            } else {
                formData['recommend'] = 1;
            }
            this.update(id, formData, '推荐修改成功');
        },
        update (id, data, message) {
            util.ajax.post('/busine/activity/detail', util.toFormData({
                id: id
            })).then(res => {
                let formData = res.data.data;
                for (var key in data) {
                    formData[key] = data[key];
                }
                util.ajax.post('/busine/activity/save', util.toFormData(formData)).then(res => {
                    if (res.data.message === 'SUCCESS') {
                        this.$Message.success(message);
                        this.loadList();
                    } else {
                        this.$Message.warning(res.data.message || '未知错误！');
                    }
                });
            });
        }
    }
}